package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    //新增
    @Override
    public Cart save(Cart cartParam) {
        //1. 查询当前菜品/套餐在数据表中是否存在(当前登录用户user_id)
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.eq(cartParam.getDishId() !=null,Cart::getDishId,cartParam.getDishId());//菜品id=传入的菜品id
        wrapper.eq(cartParam.getSetmealId() !=null,Cart::getSetmealId,cartParam.getSetmealId());//套餐id=传入的套餐id
        Cart cart=cartMapper.selectOne(wrapper);
        //2. 查到了当前菜品/套餐在数据库的记录,  只需要将number+1 更新
        if (cart != null){
            cart.setNumber(cart.getNumber()+1);
            cartMapper.updateById(cart);
            return cart;
        }else {
            //3. 没有查到当前菜品/套餐的记录, 新增记录
            cartParam.setUserId(UserHolder.get().getId());//添加user_id
            cartParam.setNumber(1);
            cartParam.setCreateTime( new Date());//保存新增时间
            cartMapper.insert(cartParam);
            return cartParam;
        }
    }
    //查询
    @Override
    public List<Cart> findList() {
        //select * from cart where user_id = 登录id
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        List<Cart> cartList=cartMapper.selectList(wrapper);
        return cartList;
    }
    //删除
    @Override
    public void delete() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
    //更新
    @Override
    public Cart update(Cart cartParam) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        wrapper.eq(cartParam.getDishId() != null,Cart::getDishId,cartParam.getDishId());
        wrapper.eq(cartParam.getSetmealId() != null,Cart::getSetmealId,cartParam.getSetmealId());
        Cart cart = cartMapper.selectOne(wrapper);
        if (cart.getNumber()-1 ==0){
            cartMapper.deleteById(cart);
            return cart;
        }else {
            cart.setNumber(cartParam.getNumber()-1);
            cartMapper.updateById(cart);
            return cartParam;
        }
    }

}
